/*
 * Copyright 2009 Prime Technology.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.primefaces.optimus.navigationhandler;

import java.io.IOException;

import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.application.ViewHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

public class ViewIdBasedNavigationHandler extends NavigationHandler{

    public final static String REDIRECT_PREFIX = "redirect";

    @Override
    public void handleNavigation(FacesContext facesContext, String fromAction, String outcome) {
        if(outcome == null)
            return;            //no navigation

        ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
        String targetViewId = getTargetViewId(facesContext, outcome);

        if(isRedirect(outcome))
        {
             ExternalContext externalContext = facesContext.getExternalContext();
             String redirectPath = viewHandler.getActionURL(facesContext, targetViewId);

             try
             {
                 externalContext.redirect(externalContext.encodeActionURL(redirectPath));
             }
             catch (IOException e)
             {
                 throw new FacesException(e.getMessage(), e);
             }
        }
        else
        {
            UIViewRoot viewRoot = viewHandler.createView(facesContext, targetViewId);
            facesContext.setViewRoot(viewRoot);
            facesContext.renderResponse();
        }
    }

    private boolean isRedirect(String outcome) {
        return outcome.startsWith(REDIRECT_PREFIX);
    }

    private String getTargetViewId(FacesContext facesContext, String outcome) {
        String targetViewId;
        String viewSuffix = getDefaultViewSuffix(facesContext);

        if(isRedirect(outcome)) {
            targetViewId = "/" + outcome.split(":")[1] + viewSuffix;
        } else {
            targetViewId = "/" + outcome + viewSuffix;
        }

        return targetViewId;
    }

    private String getDefaultViewSuffix(FacesContext facesContext) {
        String suffix = facesContext.getExternalContext().getInitParameter("javax.faces.DEFAULT_SUFFIX");

        return suffix!=null ? suffix : ".jsp";
    }

}

